from PIL import Image, ImageDraw, ImageFont
import random

def generate_image(output_path="generated_image.png", width=800, height=600):
    # 创建一个白色背景的图片
    image = Image.new('RGB', (width, height), color='white')
    draw = ImageDraw.Draw(image)
    
    # 绘制随机颜色的矩形
    for _ in range(5):
        x1 = random.randint(0, width//2)
        y1 = random.randint(0, height//2)
        x2 = random.randint(width//2, width)
        y2 = random.randint(height//2, height)
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        draw.rectangle([(x1, y1), (x2, y2)], fill=color, outline='black', width=2)
    
    # 绘制随机颜色的圆形
    for _ in range(3):
        x = random.randint(50, width-50)
        y = random.randint(50, height-50)
        radius = random.randint(20, 80)
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        draw.ellipse([(x-radius, y-radius), (x+radius, y+radius)], fill=color, outline='black', width=2)
    
    # 尝试加载字体并添加文字
    try:
        # 使用系统字体，如果找不到则使用默认字体
        font = ImageFont.truetype("arial.ttf", 36)
    except:
        font = ImageFont.load_default()
    
    draw.text((width//2 - 100, height//2 - 18), "Generated Image", font=font, fill='black')
    
    # 保存图片
    image.save(output_path)
    print(f"图片已保存至: {output_path}")
    # 显示图片
    image.show()

if __name__ == "__main__":
    generate_image()
    